import { getMenuData } from "@ant-design/pro-components";
import { useInfo } from "@/hooks/useInfo";
import { routes } from "@/routes";

import type { IRoute } from "@/routes";


export const clapMenus = (routes: IRoute[]): { layoutRoutes: IRoute[], commonRoutes: IRoute[] } => {
  const layoutRoutes: IRoute[] = [];
  const commonRoutes: IRoute[] = [];
  for (let index = 0; index < routes.length; index++) {
    const item = routes[index];
    if (item) {
      if (item.layout) {
        if (item.children) {
          layoutRoutes.push(...item.children)
        } else {
          layoutRoutes.push(item)
        }
      } else {
        if (item.children) {
          commonRoutes.push(...item.children)
        } else {
          commonRoutes.push(item)
        }
      }
    }
  }
  return { layoutRoutes, commonRoutes };
}

export const filterRoutes = (routes: IRoute[], filterCondition: Function): IRoute[] => {
  const newRoutes = routes.map((route: IRoute) => {
    if (filterCondition(route)) {
      if (route.children) {
        return { ...route, children: filterRoutes(route.children, filterCondition) };
      } else {
        return route
      }
    } else {
      return null;
    }
  }).filter(route => route !== null);
  return newRoutes as IRoute[];
};

export const getPremissionRoutes = (routes: IRoute[], menus: string[]) => {
  return filterRoutes(routes, (route: IRoute) => route.path && menus.includes(route.path));
}
export const useMenu = () => {
  const { userMenus } = useInfo();
  const { layoutRoutes } = clapMenus(routes);

  const premissionPaths: string[] = [];
  const premissionMaps: { [key: string]: number[] } = {};

  userMenus.forEach((menu) => {
    if (menu.path) {
      premissionPaths.push(menu.path);
      premissionMaps[menu.path] = menu.operations || [];
    }
  });

  const premissionRoutes = getPremissionRoutes(layoutRoutes, premissionPaths);
  const { menuData, breadcrumb } = getMenuData(premissionRoutes);

  return {
    premissionPaths,
    premissionRoutes,
    premissionMaps,
    menuData,
    breadcrumb
  }
};

export default useMenu;
